//
//  SpeakOthers.m
//  group14
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 吕志伟. All rights reserved.
//

#import "SpeakOthers.h"
#import <AVOSCloudIM/AVOSCloudIM.h>

#define kChatSql [ChatRecordSql shareChatRecordSql]
@interface SpeakOthers ()<AVIMClientDelegate>

@property (nonatomic, strong) AVIMClient *client;

@property (nonatomic, copy) NSString *idStr;

@end

@implementation SpeakOthers

+ (SpeakOthers *)shareSpeakOthers
{
    static SpeakOthers * speak = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        speak = [[SpeakOthers alloc] init];
    });
    return speak;
}

- (void)receiveMessage:(NSString *)userName {
    // Jerry 创建了一个 client
    self.client = [[AVIMClient alloc] init];
    
    // 设置 client 的 delegate，并实现 delegate 方法
    self.client.delegate = self;
    
    // Jerry 用自己的名字作为 ClientId 打开了 client
    [self.client openWithClientId:userName callback:^(BOOL succeeded, NSError *error) {
        // ...
    }];
}

#pragma mark - AVIMClientDelegate

// 接收消息的回调函数
- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message {
    
    message.attributes = [NSDictionary dictionaryWithObject:@"YES" forKey:@"isOutgoing"];
    
    NSLog(@"收到的消息%@", message.text);
    
    AVUser *user = [AVUser currentUser];
    
    AVQuery *query = [AVQuery queryWithClassName:@"_Conversation"];
    
    NSString *creatStr = [NSString stringWithFormat:@"%@and%@",user.username,message.clientId];
    
    [query whereKey:@"name" equalTo:creatStr];
    
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        
        _idStr = [object objectForKey:@"objectId"];
        
        if(!object)
        {
            [self.client createConversationWithName:creatStr clientIds:@[message.clientId] callback:^(AVIMConversation *conversation, NSError *error)
             {
                 self.myblock(message);
             }];
        }
        else
        {
            
            AVIMConversationQuery *query = [self.client conversationQuery];
            [query getConversationById:_idStr callback:^(AVIMConversation *conversation, NSError *error) {
                self.myblock(message);
            }];
        }
        
        
    }];

    
    
}


@end
